<template>
  <div class="container" style="height: 100vh;min-width: 300px;padding: 20px;box-sizing: border-box;width: 100%;">
    <header>
      <MBreadcrumb :item="breadcrumbItem" />
    </header>
    <main>
      <MTitle class="title">
        <template #left>
          产品参数
        </template>
      </MTitle>
      <form>
        <table id="attributeTable" class="mtable">
          <tr class="mtr">
            <td class="field">品类</td>
            <td class="value" style="height: 26px;line-height: 26px;">
              {{ productName }}
            </td>
          </tr>
          <tr v-for="(obj, index) in MListItem" :key="index" class="mtr">
            <td class="field">{{ obj.field }}</td>
            <td class="value" v-if="String(obj.field) != '适用蚀刻液类型'">
              <MInput v-model="ProductInfo[index]" style="font-size: 12px;width: 90%"></MInput>
            </td>
            <td class="value" v-else>
              <MSelect v-model="ProductInfo[index]" :options="options" :value="ProductInfo[index]" required
                style="flex: 1 1 200px;width: 90%">
              </MSelect>
            </td>
          </tr>
        </table>
      </form>
      <MTitle class=" title1">
        <template #left>
          产品标识
        </template>
      </MTitle>
      <MList :item="MListItem2"></MList>
    </main>

    <footer>
      <MButton @click="registerCode" v-if="!setIsDisable">注册</MButton>
    </footer>
    <MMessage v-if="toastVisible" :message="toastMessage" :state="toastState" />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import MBreadcrumb from "../components/MBreadcrumb.vue"
import MTitle from "../components/MTitle.vue"
import MList from "../components/MList.vue"
import MButton from "../components/MButton.vue"
import axios from "../axios/axios"
import MInput from '@/components/MInput.vue';
import MMessage from '../components/MMessage.vue';
import MSelect from '../components/MSelect.vue';

export default {
  name: "ProductRegister",
  components: {
    MBreadcrumb,
    MTitle,
    MList,
    MButton,
    MInput,
    MMessage,
    MSelect
  },

  setup() {
    const toastVisible = ref(false)
    const toastMessage = ref("")
    const toastState = ref("success")
    const code = ref("")
    const MListItem = ref([])
    const ProductInfo = ref([])
    const MListItem2 = ref([])
    const params = ref("")
    const setIsDisable = ref(false)
    const userId = ref("")
    const productName = ref("")
    const options = ref([
      { value: '酸性', text: '酸性' },
      { value: '碱性', text: '碱性' },
    ])
    const breadcrumbItem = ref(
      {
        key: "0",
        title: '赋码管理',
        children: {
          key: "0-0",
          title: '产品注册',
        }
      })

    MListItem2.value = [
      {
        key: 1,
        field: "MA标识",
        value: code
      },
    ]
    const messageShow = (msg, state) => {
      toastMessage.value = msg;
      toastVisible.value = true;
      toastState.value = state
      // 使用 setTimeout 模拟 Toast 组件内部的定时器功能（仅用于演示）
      // 在实际使用中，你应该依赖 Toast 组件内部的定时器
      setTimeout(() => {
        toastVisible.value = false;
      }, 3000); // 与 Toast 组件中的 duration 属性保持一致
    }
    const registerCode = () => {
      if (chectValue()) {
        var dataList = [...MListItem.value]
        var a = []
        var modelInfo = ""
        dataList.forEach((item, index) => {
          if (item.field == "型号") {
            modelInfo = ProductInfo.value[index]
          }
          a.push({
            title: item.field,
            value: ProductInfo.value[index],
          })
        })
        a.push({
          title: "品类",
          value: productName.value,
        })

        axios.post('/register/register?userId=' + userId.value, {
          appid: params.value.get('AppId'),
          trainingid: params.value.get("trainingId"),
          productinfo: JSON.stringify(a),
          productmodel: modelInfo
        })
          .then(response => {
            if (response.data.Code == "200") {
              code.value = response.data.Data
            } else {
              messageShow(response.data.Msg, "warning")

            }
          })
      }

    }
    const chectValue = () => {

      const hasEmpty = ProductInfo.value.some(function (item, index) {
        if (item === "") {
          messageShow("请输入" + MListItem.value[index].field, "warning");
          return true;
        }
        return false;
      });

      return !hasEmpty;

    }

    onMounted(() => {
      // 获取 URL 参数
      const param = new URLSearchParams(window.location.search);
      params.value = param
      if (param.has('AppId')) {
        const dataList = []
        const dataList1 = []
        var productType = 0
        if (param.get('productType') != null) {
          productType = (Number)(param.get('productType'))
        }
        axios.get('/product/select?appId=' + param.get('AppId') + "&userId=" + param.get("userId") + "&productType=" + productType)
          .then(response => {
            const info = JSON.parse(response.data.Data.productinfo)
            productName.value = response.data.Data.productname
            info.forEach((element, index) => {
              dataList.push({
                key: index,
                field: element.title,
                value: element.value,
              },)
              dataList1.push("")
            });
            MListItem.value = dataList
            ProductInfo.value = dataList1
          })

      }
      if (param.has('isDisable')) {
        setIsDisable.value = param.get('isDisable') === 'true';
      }
      if (param.has('userId')) {
        userId.value = param.get('userId');
      }

    });

    return {
      breadcrumbItem,
      MListItem,
      MListItem2,
      code,
      registerCode,
      chectValue,
      setIsDisable,
      ProductInfo,
      toastVisible,
      toastMessage,
      toastState,
      productName,
      options
    };
  },
  computed: {

  },
};
</script>

<style scoped>
.mtable {
  width: 100%;
  font-size: 13px;

}

.field {
  text-align: left;
  padding: 4px 0;
  flex: 1 1 60px;
  word-break: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  min-width: 0;
  /* 确保内容可以缩小 */
  height: 26px;
  line-height: 26px;
}

.value {
  text-align: right;
  padding: 4px 0;
  flex: 1 1 150px;
  word-break: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  min-width: 0;
  /* 确保内容可以缩小 */
}

.mtr {
  display: flex;
  flex-wrap: wrap;
  /* 允许子元素换行 */
  align-items: flex-start;
}

.title {
  margin-top: 30px;
}

.title1 {
  margin-top: 20px;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

footer {
  text-align: center;
  height: 10%;
  padding: 20px;
}

main {
  flex: 1;
}
</style>